package com.example.my2048.game.manager;

import static java.lang.Math.abs;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import androidx.annotation.NonNull;

import com.example.my2048.game.model.Board;
import com.example.my2048.game.view.BoardView;

public class GameSensorManager implements SensorEventListener {

    private final SensorManager sensorManager;
    private final Sensor accelerometerSensor;
    private final float[] gravity = new float[3];
    private final Board board;
    private final BoardView boardView;
    private boolean ifIncline;
    private final float[] preTiltAngle;

    public GameSensorManager(@NonNull SensorManager sensorManager, Board board, BoardView boardView) {
        this.sensorManager = sensorManager;
        accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        this.board = board;
        this.boardView = boardView;
        this.ifIncline = false;
        this.preTiltAngle = new float[]{0.0f, 0.0f};
    }

    public void registerListener() {
        sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);
    }

    public void unregisterListener() {
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(@NonNull SensorEvent event) {
        final float gravityValue = 9.8f;
        gravity[0] = event.values[0];
        gravity[1] = event.values[1];
        gravity[2] = event.values[2];
        // 计算倾斜角度
        float tiltAngleX = (float) (90.0f - Math.toDegrees(Math.acos(abs(gravity[0]) / gravityValue)));
        float tiltAngleY = (float) (90.0f - Math.toDegrees(Math.acos(abs(gravity[1]) / gravityValue)));
        if (abs(preTiltAngle[0] - tiltAngleX) <= 45 && abs(preTiltAngle[1] - tiltAngleY) <= 45) {
            return;
        }
        this.preTiltAngle[0] = tiltAngleX;
        this.preTiltAngle[1] = tiltAngleY;
        if (abs(tiltAngleX) > 45 || abs(tiltAngleY) > 45) {
            this.ifIncline = true;
        }
        if (this.ifIncline) {
            if (abs(tiltAngleX) > abs(tiltAngleY)) {
                if (gravity[0] < 0) {
                    this.board.mergeRight();
                } else {
                    this.board.mergeLeft();
                }
            } else {
                if (gravity[1] < 0) {
                    this.board.mergeUp();
                } else {
                    this.board.mergeDown();
                }
            }
            this.boardView.invalidate();
            this.ifIncline = false;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // 精度变化时的处理
    }

}